package com.ty.filter;

import com.ty.util.UserUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * {"/admin/index.jsp","/admin/views/*","/express/*"}
 *
 * @WebFilter({"/admin/index.jsp","/admin/views/*","/express/*"})
 *
 * @author 田野
 */
@WebFilter({"/admin/index.jsp","/admin/views/*","/express/*","/user/*","/courier/*"})
public class AccessControlFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("权限过滤器创建！");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        System.out.println("请求地址是：");

        String userName = UserUtil.getUserName(request.getSession());
        if (userName == null || "".equals(userName)){
            /*response.sendError(404, "权限不足！");*/
            response.sendRedirect("/admin/login.html");
        }
        /*HttpSession session = request.getSession();
        Object wxUser = session.getAttribute("WxUser");
        Object wxCourier = session.getAttribute("WxCourier");
        if (wxUser == null && wxCourier == null){
            response.sendRedirect("/login.html");
        }*/

        // 执行下一个过滤器
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
